package com.chinanet.auth;

import com.chinanet.oracle.entry.User;
import com.chinanet.oracle.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class LoginAuthenticationManager implements AuthenticationManager {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println(authentication.getCredentials());

        User user = userRepository.findByAccount(authentication.getPrincipal().toString());
        if (user != null) {
            if (authentication.getCredentials().equals(user.getPsw())) {
                System.out.println("认证成功");
                return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Arrays.<SimpleGrantedAuthority>asList(new SimpleGrantedAuthority(user.getRole().getRoleName())));
            }else {
                throw new BadCredentialsException("密码错误");
            }
        }else{
            // 认证失败
            throw new BadCredentialsException("用户名不存在");
        }
    }
}
